package com.atguigu.flink.datastreamapi.transform;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2022/12/13
 *
 *  reduce:
 *              用于两两聚合。第一条数据来不执行！
 *              要求输入和输出的类型必须一致
 *                  (T t1,T t2) ---> T t3
 *
 *    ------------
 *    求每种传感器vc的最大值
 */
public class Demo8_Reduce
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .keyBy(WaterSensor::getId)
                   .reduce(new ReduceFunction<WaterSensor>()
                   {
                       /*
                             WaterSensor value1：上一次聚合的结果
                             WaterSensor value2： 当前到来的数据
                        */
                       @Override
                       public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {

                           System.out.println("Demo8_Reduce.reduce");

                           //取最大的vc + 最大vc的WaterSensor的所有属性
                           //return value1.getVc() >= value2.getVc() ? value1 : value2 ;
                           //取最大的vc + 最新的WaterSensor的所有属性
                           value2.setVc(Math.max(value1.getVc(),value2.getVc()));

                           return value2;
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
